package com.djhu.springsimple.beans.factory;

import com.djhu.springsimple.beans.core.BeanDefinition;
import com.djhu.springsimple.beans.core.BeanReference;
import com.djhu.springsimple.beans.core.PropertyValue;

import java.lang.reflect.Method;

/**
 * @author by zw on 2018/4/16.
 */
public class AutowireBeanFactory extends BaseBeanFactory{
    @Override
    protected Object applyPropertyValues(Object bean, BeanDefinition beanDefinition) throws Exception {
        for (PropertyValue propertyValue:   beanDefinition.getPropertyValues().getPropertyValues()){
            Object value = null;
            if (propertyValue.getValue() instanceof BeanReference){
                BeanReference beanReference = (BeanReference)(propertyValue.getValue());
                value = getBean(beanReference.getBeanName());
            }
            String methodName ="set" + propertyValue.getName().substring(0, 1).toUpperCase() + propertyValue.getName().substring(1);
            Method method = beanDefinition.getBeanClass().getMethod(methodName,value.getClass());
            method.setAccessible(true);
            method.invoke(bean,value);
        }
        return bean;
    }
}